import * as vscode from 'vscode';
import * as child_process from 'child_process';
import * as path from 'path';
import * as fs from 'fs';

// 检查Biome环境是否可用
async function checkBiomeEnvironment(): Promise<boolean> {
	try {
		// 检查当前工作区是否有package.json
		const workspaceFolders = vscode.workspace.workspaceFolders;
		if (!workspaceFolders || workspaceFolders.length === 0) {
			return false;
		}

		const workspaceRoot = workspaceFolders[0].uri.fsPath;
		const packageJsonPath = path.join(workspaceRoot, 'package.json');
		
		// 检查package.json是否存在
		if (fs.existsSync(packageJsonPath)) {
			const packageJsonContent = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
			
			// 检查dependencies或devDependencies中是否有biome
			const dependencies = {
				...packageJsonContent.dependencies,
				...packageJsonContent.devDependencies
			};
			
			if (dependencies && (dependencies.biome || dependencies['@biomejs/biome'])) {
				return true;
			}
		}

		// 检查全局安装的Biome
		return new Promise<boolean>((resolve) => {
			const checkCommand = process.platform === 'win32' ? 'where biome' : 'which biome';
			
			child_process.exec(checkCommand, (error, stdout) => {
				if (error) {
					// 检查pnpm dlx biome
					child_process.exec('pnpm dlx biome --version', (error2) => {
						resolve(!error2);
					});
				} else {
					resolve(stdout.trim().length > 0);
				}
			});
		});
	} catch (error) {
		return false;
	}
}

// 显示Biome环境检查警告
async function showBiomeEnvironmentWarning() {
	const hasBiome = await checkBiomeEnvironment();
	
	if (!hasBiome) {
		const selection = await vscode.window.showWarningMessage(
			'Biome环境未检测到。插件需要Biome才能正常工作。',
			'安装Biome',
			'查看文档',
			'忽略'
		);
		
		if (selection === '安装Biome') {
			// 打开Biome安装文档
			vscode.env.openExternal(vscode.Uri.parse('https://biomejs.dev/guides/getting-started/'));
		} else if (selection === '查看文档') {
			// 打开插件使用文档
			vscode.env.openExternal(vscode.Uri.parse('https://github.com/your-username/test-biome#readme'));
		}
	}
	
	return hasBiome;
}

// 当插件被激活时调用此方法
// 你的插件在第一次执行命令时被激活
export function activate(context: vscode.ExtensionContext) {
	
	console.log('Congratulations, your extension "test-biome" is now active!');

	// 注册Hello World命令
	let helloWorldDisposable = vscode.commands.registerCommand('test-biome.helloWorld', () => {
		// 显示消息框给用户
		vscode.window.showInformationMessage('Hello World from test-biome!');
	});

	// 在插件激活时检查Biome环境
	showBiomeEnvironmentWarning();

	// 注册Biome Check命令（支持文件和文件夹）
	let disposable = vscode.commands.registerCommand('test-biome.biomeCheckFile', async (uri?: vscode.Uri) => {
		// 在执行命令前检查Biome环境
		const hasBiome = await checkBiomeEnvironment();
		if (!hasBiome) {
			vscode.window.showErrorMessage('Biome环境未检测到。请先安装Biome才能使用此功能。');
			return;
		}
		// 获取当前路径（文件或文件夹）
		let targetPath: string | undefined;
		let isDirectory = false;
		
		if (uri && uri.fsPath) {
			// 从右键菜单传递的URI获取路径
			targetPath = uri.fsPath;
			// 检查是否为文件夹
			try {
				const stat = await vscode.workspace.fs.stat(uri);
				isDirectory = stat.type === vscode.FileType.Directory;
			} catch (error) {
				// 如果无法获取文件状态，默认为文件
				isDirectory = false;
			}
		} else {
			// 从当前活动的编辑器获取文件路径
			const editor = vscode.window.activeTextEditor;
			if (editor) {
				targetPath = editor.document.uri.fsPath;
				isDirectory = false;
			}
		}

		if (!targetPath) {
			vscode.window.showErrorMessage('无法获取路径，请确保已打开文件或右键点击了文件/文件夹');
			return;
		}

		// 如果是文件，检查文件格式
		if (!isDirectory) {
			const supportedExtensions = ['.js', '.ts', '.jsx', '.tsx', '.json'];
			const fileExt = path.extname(targetPath).toLowerCase();
			
			if (!supportedExtensions.includes(fileExt)) {
				vscode.window.showErrorMessage(`不支持的文件格式: ${fileExt}。仅支持: ${supportedExtensions.join(', ')}`);
				return;
			}
		}

		// 执行Biome Check命令
		try {
			await runBiomeCheck(targetPath, isDirectory);
		} catch (error) {
			vscode.window.showErrorMessage(`执行Biome Check失败: ${error}`);
		}
	});

	context.subscriptions.push(helloWorldDisposable, disposable);
}

// 创建输出通道
let outputChannel: vscode.OutputChannel;

// 运行Biome Check命令（支持文件和文件夹）
async function runBiomeCheck(targetPath: string, isDirectory: boolean): Promise<void> {
	// 创建或获取输出通道
	if (!outputChannel) {
		outputChannel = vscode.window.createOutputChannel('Biome Check');
	}
	
	// 显示输出通道
	outputChannel.show(true);
	
	// 显示进度通知
	const progressTitle = isDirectory ? `Running Biome Check on folder: ${path.basename(targetPath)}...` : 'Running Biome Check...';
	
	await vscode.window.withProgress({
		location: vscode.ProgressLocation.Notification,
		title: progressTitle,
		cancellable: false
	}, async (progress) => {
		return new Promise<void>((resolve, reject) => {
			// 构建命令
			const command = 'pnpm';
			const args = ['biome', 'check', targetPath, '--write'];
			
			// 获取当前工作目录
			const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(targetPath));
			let cwd: string;
			
			if (isDirectory) {
				// 如果是文件夹，使用文件夹本身作为工作目录
				cwd = targetPath;
			} else {
				// 如果是文件，使用文件所在目录
				cwd = workspaceFolder ? workspaceFolder.uri.fsPath : path.dirname(targetPath);
			}

			// 输出命令信息
			outputChannel.appendLine(`[${new Date().toLocaleTimeString()}] 执行 Biome Check:`);
			outputChannel.appendLine(`命令: ${command} ${args.join(' ')}`);
			outputChannel.appendLine(`工作目录: ${cwd}`);
			outputChannel.appendLine('---');

			// 执行命令
			const process = child_process.spawn(command, args, {
				cwd: cwd,
				shell: true,
				stdio: 'pipe'
			});

			let stdout = '';
			let stderr = '';

			process.stdout.on('data', (data) => {
				const output = data.toString();
				stdout += output;
				outputChannel.append(output);
			});

			process.stderr.on('data', (data) => {
				const output = data.toString();
				stderr += output;
				outputChannel.append(output);
			});

			process.on('close', (code) => {
				outputChannel.appendLine('---');
				if (code === 0) {
					const successMessage = isDirectory 
						? `Biome Check 完成: 文件夹 ${path.basename(targetPath)}` 
						: `Biome Check 完成: ${path.basename(targetPath)}`;
					outputChannel.appendLine(`✅ ${successMessage}`);
					outputChannel.appendLine('');
					resolve();
				} else {
					outputChannel.appendLine(`❌ Biome Check 失败 (退出码: ${code})`);
					reject(new Error(`Biome Check 失败 (退出码: ${code}): ${stderr || stdout}`));
				}
			});

			process.on('error', (error) => {
				outputChannel.appendLine(`❌ 执行命令失败: ${error.message}`);
				reject(new Error(`执行命令失败: ${error.message}`));
			});
		});
	});
}

// 当插件被停用时调用此方法
export function deactivate() {
	if (outputChannel) {
		outputChannel.dispose();
	}
}